package com.xundao.yxt.framework.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 假设从数据库中获取用户角色和权限
        Set<String> roles = getRolesByUsername(username);
        Set<String> permissions = getPermissionsByUsername(username);

        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(permissions);
        return authorizationInfo;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        // 假设从数据库中获取用户密码
        String password = getPasswordByUsername(username);
        if (password == null) {
            throw new AuthenticationException("用户不存在");
        }
        return new SimpleAuthenticationInfo(
                username,
                password,
                getName()
        );
    }

    private Set<String> getRolesByUsername(String username) {
        Set<String> roles = new HashSet<>();
        // 模拟从数据库查询用户角色
        if ("admin".equals(username)) {
            roles.add("admin");
        } else {
            roles.add("user");
        }
        return roles;
    }

    private Set<String> getPermissionsByUsername(String username) {
        Set<String> permissions = new HashSet<>();
        // 模拟从数据库查询用户权限
        if ("admin".equals(username)) {
            permissions.add("user:view");
            permissions.add("user:edit");
        } else {
            permissions.add("user:view");
        }
        return permissions;
    }

    private String getPasswordByUsername(String username) {
        // 模拟从数据库查询用户密码
        if ("admin".equals(username)) {
            return "admin123";
        } else if ("user".equals(username)) {
            return "user123";
        }
        return null;
    }
}
